<?php

namespace Beerus\Modules\BrokeNews\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel;
use Biz\model\brandActivity\BrandActivityBasic;
use Biz\model\FineGoodsBrokeNews\FineGoodsBrokeNewsFavouriteLogModel;
use Biz\model\wiki\Wiki;
use Biz\model\wiki\WikiBasic;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class IndexController extends Controller
{
    const PAGE_LIMIT = 25;

    public function list(Request $request, Content $content,$id=0): Content
    {
        $page = $request->input("page", 1);
        $id = $request->input("id", "");
        $where = [];
        $title = $request->input("title", "");
        if ($id !== "") {
            $where['basic_id'] = $id;
        }
        if ($title !== "") {
            $paramList = WikiBasic::select("id",[
                'title[~]' => "%{$title}%"
            ]);
            $where['basic_id'] = $paramList;
        }
        $total = FineGoodsBrokeNewsFavouriteLogModel::count($where);
        $where['LIMIT'] = [($page - 1) * self::PAGE_LIMIT, self::PAGE_LIMIT];
        $where['ORDER'] = ['id' => "DESC"];
        $list = FineGoodsBrokeNewsFavouriteLogModel::select(['basic_id', 'fav_count'], $where);
        $basicID = array_column($list, 'basic_id');
        if (!empty($basicID)) {
            $titleList = WikiBasic::select(['id', 'title'],
                ['id' => $basicID]);
            $titleMap = array_column($titleList, 'title', 'id');
            foreach ($list as $index => $item) {
                $list[$index]['title'] = $titleMap[$item['basic_id']];
                $list[$index]['id'] = $item['basic_id'];
            }
        }
        $gridModel = new GridDataModel($list, $total, [
            'perPage' => self::PAGE_LIMIT,
        ]);
        $grid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel) {
            $grid->paginate($gridModel->getPerPage());
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->disableActions();
            $grid->filter(function ($filter) {
                // 在这里添加字段过滤
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('title', '标题')->placeholder('标题');
                });
                $filter->expand();//默认展开
            });
            $grid->column('basic_id', '主键ID');
            $grid->column('title', '标题');
            $grid->column('fav_count', '收藏数')->editable();
        });
        $tab = new Tab();
        $tab->add('修改收藏数', $grid->render(), true);
        $content->row($tab);
        return $content
            ->header('好物爆料 修改收藏数')
            ->description(' ');
    }

    public function modifyFav(Request $request, Content $content,$id = 0)
    {
        $favCount = $request->input("value");
        $basicID = $request->input("pk");
        $log = FineGoodsBrokeNewsFavouriteLogModel::select("fav_count",['basic_id' => $basicID]);
        if(empty($log)){
            FineGoodsBrokeNewsFavouriteLogModel::insert([
                'basic_id' => $basicID,
                'fav_count' => $favCount,
                'log_time' => date("Y-m-d H:00:00")
            ]);
        }else{
            FineGoodsBrokeNewsFavouriteLogModel::update(['fav_count' => $favCount],['basic_id' => $basicID]);
        }
        return response()->json(['status' => true,'message' => "修改成功"]);
    }

    public function index(Request $request, Content $content): Content
    {
        $baseForm = new Form(['wiki_id' => '', 'fav_count' => '']);
        $baseForm->action("/admin/brokeNews/save");
        $baseForm->disableReset();
        $baseForm->html('<div class="btn-group pull-right">
                <input type="button" id="search" class="btn btn-info pull-right" value="查询">
                <button type="submit" class="btn btn-info pull-right">提交</button>
            </div>');
        $baseForm->text('wiki_id', 'wiki ID');
        $baseForm->text('fav_count', '收藏数');
        $baseForm->html("<iframe src='' id='wiki-box' style='border:0;width:100%;height:500px'></iframe>");
        Admin::script($this->script());
        return $content
            ->header('修改Wiki收藏数')
            ->description(' ')
            ->breadcrumb(
                ['text' => '修改Wiki收藏数']
            )
            ->row($baseForm);
    }

    public function save(Request $request, Content $content)
    {
        $wikiID = $request->post('wiki_id', '');
        $favCount = $request->post('fav_count', '');
        $basicID = Wiki::get("basic_id", ['id' => $wikiID]);
        FineGoodsBrokeNewsFavouriteLogModel::update(['fav_count' => $favCount], ['basic_id' => $basicID]);
        $success = new MessageBag([
            'title' => '修改成功'
        ]);
        return redirect('/admin/brokeNews/index')->with(compact("success"));
    }

    private function script()
    {
        return <<<EOF
document.querySelector('#search').onclick = function(){
   var baseID = document.querySelector('#wiki_id').value;
   document.querySelector('#wiki-box').setAttribute('src',"/admin/wiki/admList/" + baseID + "/edit");
   $('#wiki-box').load(function() {
        setTimeout(function() {
            $(window.frames[0].document).find("input,button,select,checkout,radio,textarea,button").prop('disabled',true);
            $(window.frames[0].document).find(".navbar,.sidebar,.main-sidebar,.main-header").remove();
        },100);
   })
}
EOF;
    }
}